import { Module, Provider } from '@nestjs/common';
import { DatabaseProvider } from './database.provider';
import { Connection, Model } from 'mongoose';
import { SchemaFactory } from '@nestjs/mongoose';
import { Constants } from '../constants/constants';
import { ConfigModule } from '@nestjs/config';
import databaseConfig from '../config/database.config';

@Module({
  imports: [ConfigModule.forFeature(databaseConfig)],
  providers: [...DatabaseProvider],
  exports: [...DatabaseProvider]
})
export class DatabaseModule {
  /**
   * schema model provider generator
   * @param modelProps
   */
  static modelProviders(modelProps: ModelProp[]): Provider[] {
    return modelProps.map((model) => ({
      provide: model.name,
      useFactory: (connection: Connection): Model<typeof model.clazz> =>
        connection.model(
          model.clazz.name,
          SchemaFactory.createForClass(model.clazz)
        ),
      inject: [Constants.CONNECTION.PROVIDER]
    }));
  }
}

interface ModelProp {
  name: string;
  clazz: any;
}
